//
//  NewHomeMiaoSha.m
//  KYRR
//
//  Created by kuyuZJ on 2017/4/19.
//
//

#import "NewHomeMiaoSha.h"
#import "ZQCountDownView.h"

@interface NewHomeMiaoSha ()

@property(nonatomic,strong) UIView* topView;
@property(nonatomic,strong) UILabel* labelMiaoSha;
@property(nonatomic,strong) UILabel* labelTime;
@property(nonatomic,strong) ZQCountDownView* timer;
@property(nonatomic,strong) UIView* middleView;
@property(nonatomic,strong) UIImageView* logo;
@property(nonatomic,strong) UIView* rightView;
@property(nonatomic,strong) UILabel* labelTitle;
@property(nonatomic,strong) UILabel* labelStoreName;
@property(nonatomic,strong) UILabel* labelPrice;
@property(nonatomic,strong) UIButton* btnBuy;

@property(nonatomic,assign) NSInteger sumTime;

@end

@implementation NewHomeMiaoSha{
    CGFloat topHeight;
    CGSize logoSize,timerSize;
}

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        self.backgroundColor = [UIColor whiteColor];
        topHeight = 40.f;
        logoSize = CGSizeMake(80.f, 80.f);
        timerSize = CGSizeMake(80.f, 20.f);
        [self addSubview:self.topView];
        [self.topView addSubview:self.labelMiaoSha];
        [self.topView addSubview:self.labelTime];
        [self.topView addSubview:self.timer];
        [self addSubview:self.middleView];
        [self.middleView addSubview:self.logo];
        [self.middleView addSubview:self.rightView];
        [self.rightView addSubview:self.labelTitle];
        [self.rightView addSubview:self.labelStoreName];
        [self.rightView addSubview:self.labelPrice];
        [self.rightView addSubview:self.btnBuy];
        
        NSArray<NSString*>* formats = @[@"H:|-leftEdge-[topView]-leftEdge-|",@"H:|-leftEdge-[middleView]-leftEdge-|",
                                        @"V:|-defEdge-[topView(==topHeight)][middleView]-topEdge-|",
                                       
                                        @"H:|-defEdge-[labelMiaoSha][labelTime]-5-[timer(==timerWidth)]-defEdge-|",
                                        @"V:|-defEdge-[labelMiaoSha]-defEdge-|", @"V:|-defEdge-[labelTime]-defEdge-|", @"V:[timer(==timerHeight)]",
                                        
                                        @"H:|-leftEdge-[logo(==logoWidth)]-leftEdge-[rightView]-leftEdge-|",
                                        @"V:|-topEdge-[logo(==logoHeight)]-topEdge-|", @"V:|-topEdge-[rightView]-topEdge-|",
                                       
                                        @"H:|-defEdge-[labelTitle]-defEdge-|",@"H:|-defEdge-[labelStoreName]-defEdge-|",@"H:|-defEdge-[labelPrice][btnBuy(==80)]-defEdge-|",
                                        @"V:|-defEdge-[labelTitle(==20)][labelStoreName][labelPrice(==20)]-defEdge-|", @"V:[btnBuy(==25)]-defEdge-|"
                                        ];
        NSDictionary<NSString*,id>* metrics = @{ @"defEdge":@(0), @"leftEdge":@(10), @"topEdge":@(10),
                                                 @"topHeight":@(topHeight), @"logoWidth":@(logoSize.width), @"logoHeight":@(logoSize.height),
                                                 @"timerWidth":@(timerSize.width), @"timerHeight":@(timerSize.height)
                                                 };
        NSDictionary<NSString*,id>* views = @{ @"topView":self.topView, @"middleView":self.middleView,
                                               @"labelMiaoSha":self.labelMiaoSha, @"labelTime":self.labelTime, @"timer":self.timer,
                                               @"logo":self.logo, @"rightView":self.rightView,
                                               @"labelTitle":self.labelTitle, @"labelStoreName":self.labelStoreName, @"labelPrice":self.labelPrice, @"btnBuy":self.btnBuy
                                               };
        [formats enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSLog( @"%@ %@",[self class],obj);
            NSArray<NSLayoutConstraint*>* constraints = [NSLayoutConstraint constraintsWithVisualFormat:obj options:0 metrics:metrics views:views];
            [self addConstraints:constraints];
        }];
        
        [self.topView addConstraint:[NSLayoutConstraint constraintWithItem:self.timer attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.topView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.f]];
       
    }
    return self;
}

-(void)setItem:(NSDictionary *)item{
    if(item){
        _item = item;
        [self.logo sd_setImageWithURL:[NSURL URLWithString:[item objectForKey: @"default_image"]] placeholderImage:nil options:SDWebImageRefreshCached];
        
        NSString* startTimeStr = [item objectForKey: @"startdate"];
        NSDate* beginDate = [WMHelper convertToDateWithStr:startTimeStr format:@"yyyy-MM-dd HH:mm:ss"];
        NSDate* nowDate = [NSDate date];
        NSTimeInterval beginInterval= [nowDate timeIntervalSinceDate:beginDate];
        
        NSString* endTimeStr = [item objectForKey: @"enddate"];
        NSDate* endData = [WMHelper convertToDateWithStr:endTimeStr format:@"yyyy-MM-dd HH:mm:ss"];
        NSTimeInterval endInterval = [nowDate timeIntervalSinceDate:endData];
//         self.sumTime = -10;
//        endInterval = self.sumTime;
//        beginInterval = self.sumTime;
        self.btnBuy.hidden = NO;
        if(endInterval>=0){
            self.labelTime.text =  @"已结束";
            self.btnBuy.enabled = NO;
            self.btnBuy.backgroundColor = [UIColor grayColor];
            self.timer.countDownTimeInterval = 0;
        }else{
               self.btnBuy.backgroundColor = theme_navigation_color;
            if(beginInterval>0){
                 self.labelTime.text =  @"距结束";                 
                self.timer.countDownTimeInterval = -endInterval;
                [NSTimer scheduledTimerWithTimeInterval:-endInterval target:self selector:@selector(endBuy) userInfo:nil repeats:NO];
            }else{
                 self.labelTime.text =  @"距开始";
                self.btnBuy.hidden = YES;
                self.timer.countDownTimeInterval = -beginInterval;
                [NSTimer scheduledTimerWithTimeInterval:-beginInterval target:self selector:@selector(beginBuy) userInfo:nil repeats:NO];
            }
        }
        
        self.labelTitle.text = [self.item objectForKey: @"name"];
        self.labelStoreName.text = [self.item objectForKey: @"site_name"];
        NSString* strIcon = @"￥";
        NSString* marktPrice = [NSString stringWithFormat:@"￥%@",[self.item objectForKey: @"market_price"]];
        NSString* buyNowPrice = [self.item objectForKey: @"price"];
        NSString* str = [NSString stringWithFormat:@"%@%@ %@",strIcon,buyNowPrice,marktPrice];
        NSMutableAttributedString* attributeStr = [[NSMutableAttributedString alloc] initWithString:str];
        [attributeStr addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12.f],NSForegroundColorAttributeName:[UIColor redColor]} range:NSMakeRange(0, 1)];
        [attributeStr addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17.f],NSForegroundColorAttributeName:[UIColor redColor]} range:[str rangeOfString:buyNowPrice]];
        [attributeStr addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12.f],NSForegroundColorAttributeName:[UIColor colorWithRed:146/255.f green:146/255.f blue:146/255.f alpha:1.0],NSStrikethroughStyleAttributeName:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle)} range:[str rangeOfString:marktPrice]];
        [self.labelPrice setAttributedText:attributeStr];
        
        
    }else{
        [self.logo setImage:[UIImage imageNamed:kDefaultMiaoShaImage]];
    }
}

#pragma mark =====================================================  private method
-(void)beginBuy{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString* endTimeStr = [self.item objectForKey: @"enddate"];
        NSDate* endData = [WMHelper convertToDateWithStr:endTimeStr format:@"yyyy-MM-dd HH:mm:ss"];
        NSDate* nowDate = [NSDate date];
        NSTimeInterval secondsInterval= [endData timeIntervalSinceDate:nowDate];
//        self.sumTime = 10;
//        secondsInterval = self.sumTime;
        self.btnBuy.hidden = NO;
          self.labelTime.text =  @"距结束";
          self.btnBuy.backgroundColor = theme_navigation_color;
        self.timer.countDownTimeInterval = secondsInterval;
         [NSTimer scheduledTimerWithTimeInterval:secondsInterval target:self selector:@selector(endBuy) userInfo:nil repeats:NO];
    });
}
-(void)endBuy{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.timer.countDownTimeInterval = 0;
        self.labelTime.text =  @"已结束";
        self.btnBuy.enabled = NO;
        self.btnBuy.backgroundColor = [UIColor grayColor];
    });
}


#pragma mark =====================================================  SEL
-(IBAction)btnBuyTouch:(id)sender{
    if(self.delegate && [self.delegate respondsToSelector:@selector(didSelectedMiaoSha)]){
        [self.delegate didSelectedMiaoSha];
    }
}


#pragma mark =====================================================  property package

-(UIView *)topView{
    if(!_topView){
        UIView* empty = [[UIView alloc]init];
        empty.translatesAutoresizingMaskIntoConstraints = NO;
        _topView = empty;
    }
    return _topView;
}

-(UILabel *)labelMiaoSha{
    if(!_labelMiaoSha){
        UILabel* empty = [[UILabel alloc]init];
        empty.text =  @"限时抢购";
        empty.translatesAutoresizingMaskIntoConstraints = NO;
        _labelMiaoSha = empty;
    }
    return _labelMiaoSha;
}

-(UILabel *)labelTime{
    if(!_labelTime){
        UILabel* empty = [[UILabel alloc]init];
        empty.text =  @"距开始 ";
        empty.textAlignment = NSTextAlignmentRight;
        empty.font = [UIFont boldSystemFontOfSize:12.f];
        empty.textColor = [UIColor grayColor];
        empty.translatesAutoresizingMaskIntoConstraints = NO;
        _labelTime = empty;
    }
    return _labelTime;
}

-(ZQCountDownView *)timer{
    if(!_timer){
        _timer = [[ZQCountDownView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.labelMiaoSha.frame), 0, 80, 20.f)];
        _timer.themeColor = [UIColor colorWithRed:87/255.f green:87/255.f blue:87/255.f alpha:1.0];
        _timer.textColor = [UIColor whiteColor];
        _timer.textFont = [UIFont boldSystemFontOfSize:10];
        _timer.translatesAutoresizingMaskIntoConstraints = NO;
    }
    return _timer;
}
-(UIView *)middleView{
    if(!_middleView){
        UIView* empty = [[UIView alloc]init];
        empty.backgroundColor = [UIColor colorWithRed:244/255.f green:244/255.f blue:244/255.f alpha:1.0];
        empty.translatesAutoresizingMaskIntoConstraints = NO;
        empty.userInteractionEnabled = YES;
        UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(btnBuyTouch:)];
        [empty addGestureRecognizer:tap];
        _middleView = empty;
    }
    return _middleView;
}

-(UIImageView *)logo{
    if(!_logo){
        UIImageView* empty = [[UIImageView alloc]init];
        empty.translatesAutoresizingMaskIntoConstraints = NO;
        _logo = empty;
    }
    return _logo;
}

-(UIView *)rightView{
    if(!_rightView){
        UIView* empty = [[UIView alloc]init];
//        empty.backgroundColor = [UIColor colorWithRed:244/255.f green:244/255.f blue:244/255.f alpha:1.0];
        empty.translatesAutoresizingMaskIntoConstraints = NO;
        _rightView = empty;
    }
    return _rightView;
}

-(UILabel *)labelTitle{
    if(!_labelTitle){
        UILabel* empty = [[UILabel alloc]init];
        empty.font = [UIFont systemFontOfSize:14.f];
        empty.translatesAutoresizingMaskIntoConstraints = NO;
        _labelTitle = empty;
        
    }
    return _labelTitle;
}

-(UILabel *)labelStoreName{
    if(!_labelStoreName){
        UILabel* empty = [[UILabel alloc]init];
        empty.font = [UIFont systemFontOfSize:12.f];
        empty.textColor = theme_Fourm_color;
        empty.translatesAutoresizingMaskIntoConstraints = NO;
        _labelStoreName = empty;
        
    }
    return _labelStoreName;
}

-(UILabel *)labelPrice{
    if(!_labelPrice){
        UILabel* empty = [[UILabel alloc]init];
        empty.translatesAutoresizingMaskIntoConstraints = NO;
        _labelPrice = empty;
        
    }
    return _labelPrice;
}

-(UIButton *)btnBuy{
    if(!_btnBuy){
        UIButton* empty = [UIButton buttonWithType:UIButtonTypeCustom];
        empty.backgroundColor = theme_navigation_color;
        [empty setTitle: @"立即抢购" forState:UIControlStateNormal];
        empty.titleLabel.font = [UIFont systemFontOfSize:14.f];
        empty.layer.masksToBounds = YES;
        empty.layer.cornerRadius = 3.f;
        [empty addTarget:self action:@selector(btnBuyTouch:) forControlEvents:UIControlEventTouchUpInside];
        empty.translatesAutoresizingMaskIntoConstraints = NO;
        _btnBuy = empty;
    }
    return _btnBuy;
}


@end
